package logic

import (
	"backend/apps/book/models"
	"context"
	"github.com/pkg/errors"

	"backend/apps/book/proto"
	"backend/apps/book/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetChapterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetChapterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetChapterLogic {
	return &GetChapterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetChapterLogic) GetChapter(in *proto.IdRequest) (*proto.Chapter, error) {
	chapter, err := l.svcCtx.ChapterModel.FindOne(l.ctx, in.Id)
	if err != nil {
		if errors.Is(err, models.ErrNotFound) {
			return nil, errors.New("书籍章节不存在")
		}
		return nil, err
	}
	return &proto.Chapter{
		Id:            chapter.Id,
		BookId:        chapter.BookId,
		Title:         chapter.Title,
		ChapterNumber: int32(chapter.ChapterNumber),
		PublishTime:   chapter.PublishTime.String(),
		IsFree:        int32(chapter.IsFree),
	}, nil
}
